// pages/bind.js
const Toptips = require('../../vendor/zanui/toptips/toptips')
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config')
var util = require('../../utils/util.js')

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    'stuid': ''
  },
  handleStuidBlue(event) {
    var value = event.detail.value
    if (this.stuidValidator(value)) {
      this.setData({'stuid': value})
    }
  },
  stuidValidator(value) {
    if (/^\d{8}$/.test(value)) {
      return true
    } else {
      Toptips({
        content: '请填写正确的学号',
        duration: 1000
      })
      return false
    }
  },
  bindStuid () {
    let stuid = this.data.stuid
    if (this.stuidValidator(stuid)) {
      wx.showLoading({
        title: '绑定中',
        mask: true
      });
      qcloud.request({
        url: `${config.service.host}/weapp/user/bind`,
        method: 'post',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: { stuid: stuid },
        success: res => {
          wx.hideLoading()
          if (res.data.code === 0) {
            util.showSuccess(res.data.msg)
            app.$store.stuid = stuid
            if (res.data.state === 1) {
              wx.switchTab({
                url: '../main/main'
              })
            } else if (res.data.state === 2) {
              wx.redirectTo({
                url: '../recruit/recruit'
              })
            } else if (res.data.state === 3) {
              app.$store.recruit_info = res.data.info
              wx.redirectTo({
                url: '../recruited/recruited'
              })
            }
          } else {
            util.showModel('绑定失败', res.data.error)
          }
        },
        fail: err => {
          wx.hideLoading()
          console.log(err)
          util.showModel('绑定失败', err)
        }
      })
    }
  }
})